<template>
  <div class="page-list-live">
    <el-card v-loading="logdingSwitch" class="box-card">
      <div slot="header" class="clearfix" style="background-color: #d3dbeb">
        <div style="height: 100%; overflow: hidden; display: flex; padding: 20px">
          <div class="box">
            <div>共享员工</div>
          </div>
          <el-button type="primary" :style="{ backgroundColor: shareFlag ? '' : 'rgba(88, 106, 166, 0.3)' }" :disabled="!shareFlag" :loading="confirmLoding" @click="submitHandler">确认共享</el-button>
        </div>
      </div>
      <el-row>
        <el-col :span="24">
          <div class="des">源数据员工列表置灰无法选择时证明此员工为被分享员工，请从原工点分享</div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <p>源数据</p>
          <el-tree ref="treeOne" check-strictly :data="treeData" default-expand-all show-checkbox node-key="id" :props="defaultProps" @check-change="oneHandleCheckChange" />
        </el-col>
        <el-col :span="12">
          <el-transfer v-model="value" filterable :titles="['员工列表', '员工列表']" :data="personnelList" @change="changeHandler" />
        </el-col>
        <el-col :span="6" style="margin-left: 20px">
          <p>请选择接收工点</p>
          <el-tree ref="treeTwo" :data="treeData" check-strictly default-expand-all show-checkbox :props="defaultProps" @check-change="twoHandleCheckChange" />
        </el-col>
      </el-row>
    </el-card>
    <el-card v-loading="tableLoading" class="boxDiv-card" style="margin-top: 20px">
      <!-- :span-method="objectSpanMethod"  -->
      <el-table res="tableRef" :data="tableValue" border style="width: 100%" :header-cell-style="{ backgroundColor: '#d3dbeb' }">
        <el-table-column align="center" prop="name" label="姓名" width="120" />
        <el-table-column align="center" prop="photo" label="照片" width="150">
          <template slot-scope="stData">
            <div class="demo-image__preview">
              <el-image
                :width="stData.row.width"
                style="width: 100px; height: 100px"
                :src="'data:image/jpg;base64,' + stData.row.photo"
                :preview-src-list="['data:image/jpg;base64,' + stData.row.photo]"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="toTunnel" label="分享到" width="400" />
        <el-table-column align="center" prop="newTime" label="分享日期" width="200" />
        <el-table-column align="center" prop="shareStatus" label="状态" />
        <el-table-column align="center" label="操作">
          <template slot-scope="scoped">
            <el-button
              v-loading="scoped.row.loadingDel"
              size="mini"
              type="text"
              style="border: none; padding-top: 0; padding-bottom: 0px; color: #586aa6"
              icon="el-icon-delete"
              @click="deletHandle(scoped.row)"
            >
              取消分享
            </el-button>
            <el-button
              icon="el-icon-folder-remove"
              :loading="scoped.row.loadingEdit"
              size="mini"
              style="margin-left: 10px; padding-top: 0; padding-bottom: 0px; color: #586aa6"
              type="text"
              @click="downloadHandle(scoped.row)"
            >
              下载离线共享包
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        :current-page="page.num"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="page.size"
        :total="page.total"
        style="text-align: center; margin-bottom: 20px"
        layout="total, prev, pager, next, sizes"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </el-card>
  </div>
</template>

<script>
import { MenuAll, MenuSearch, GetEmployeesByCode, ImportEmployee } from '@/api/Menu'
import { shareEmployeeHandle } from '@/api/api'
import { parseTime } from '@/utils'
import { getToken } from '@/utils/auth'
export default {
  data() {
    return {
      fromTenantCode: '',
      confirmLoding: false,
      logdingSwitch: false,
      // 左侧人员列表
      personnelList: [],
      value: [],
      // 左侧选中的人员
      checkPersonnel: [],
      // 隧道列表树
      treeData: [],
      // 右侧隧道树选中的工点
      tenantCode: [],
      // 隧道树显示的字段
      defaultProps: {
        children: 'childMenus',
        label: 'name',
        disabled: (d, n) => {
          return !(d.tenants.length > 0)
        }
      },
      // /////////////////////////////////////////////////////
      tableLoading: false,
      // 列表数据
      tableValue: [],
      ary: [],
      // 分页
      page: {
        num: 1, // 第几页
        pager: [1], // 页数
        size: 10, // 每页多少条
        total: 0, // 总共多少条数据
        lastPage: 0,
        hasPrevPage: false,
        hasNextPage: false
      }
    }
  },
  computed: {
    shareFlag() {
      const flag = this.checkPersonnel.length > 0 && this.tenantCode.length > 0
      console.log(flag)
      return flag
    }
  },
  mounted() {
    this.getMenu()
    this.getList()
  },
  methods: {
    async downloadHandle(data) {
      const url = process.env.VUE_APP_BASE_API + 'ShareEmployee/ShareOffline/' + data.id
      const xhr = new XMLHttpRequest()
      xhr.open('POST', url, true)
      xhr.setRequestHeader('content-type', 'application/octet-stream')
      xhr.setRequestHeader('Authorization', 'Bearer ' + getToken())
      xhr.setRequestHeader('x-tenant', this.$store.getters.code)
      xhr.responseType = 'blob' // 返回类型blob  blob 存储着大量的二进制数据
      xhr.onload = function (result) {
        if (xhr.status === 200) {
          const blob = this.response
          const reader = new FileReader()
          reader.readAsDataURL(blob) // 转换为base64，可以直接放入a标签href
          reader.onload = function (e) {
            var a = document.createElement('a') // 转换完成，创建一个a标签用于下载
            a.download = data.name + '共享资源包.ht'
            a.href = e.target.result
            document.body.appendChild(a) // 修复firefox中无法触发click
            a.click()
            document.body.removeChild(a)
          }
        } else {
          this.$message.error('下载失败！')
        }
      }
      xhr.send() // 发送ajax请求
    },
    // 确认共享
    async submitHandler() {
      if (!this.fromTenantCode === '') {
        this.$message.warning('请选择数据源')
        return
      }
      if (!this.checkPersonnel.length) {
        this.$message.warning('未选中共享的员工！')
        return
      } else if (!this.tenantCode.length) {
        this.$message.warning('未选中接收的工点！')
        return
      }
      this.confirmLoding = true
      try {
        await ImportEmployee({
          fromTenantCode: this.fromTenantCode,
          tenantCodes: this.tenantCode,
          employees: this.checkPersonnel
        })
        this.$message.success('共享成功！')
        this.getList()
      } catch (err) {
        console.log(err)
      }
      this.confirmLoding = false
    },
    // 左侧隧道树列表选中事件
    async oneHandleCheckChange(data, checked, indeterminate) {
      this.fromTenantCode = ''
      if (checked) {
        this.$refs.treeOne.setCheckedKeys([data.id])
        this.logdingSwitch = true
        try {
          this.personnelList = []
          const response = await GetEmployeesByCode(data.tenantCode)
          this.fromTenantCode = data.tenantCode
          this.personnelList = response.data.map((item) => {
            item.tenantCode = data.tenantCode
            return {
              key: JSON.stringify(item),
              label: item.name,
              disabled: item.employeeCode.toLowerCase().indexOf('share') > -1
            }
          })
        } catch (err) {
          console.log(err)
        }
        this.logdingSwitch = false
      }
    },
    // 右侧隧道树列表选中事件
    twoHandleCheckChange(data, checked, indeterminate) {
      if (checked) {
        this.tenantCode.push(data.tenantCode)
      } else {
        if (this.tenantCode.length > 0) {
          let inde = null
          this.tenantCode.forEach((item, index) => {
            if (item === data.tenantCode) {
              inde = index
            }
          })
          this.tenantCode.splice(inde, 1)
        }
      }
    },
    // 选中共享人员
    changeHandler(value) {
      this.checkPersonnel = value.map((item) => {
        item = JSON.parse(item)
        return item
      })
    },
    // 得到隧道树
    async getDataList(id) {
      try {
        const { data } = await MenuAll({ menuId: id })
        this.treeData = []
        this.treeData = this.getData(data)
      } catch (err) {
        console.log(err)
      }
    },
    // 处理隧道树
    getData(value) {
      value.forEach((item) => {
        if (item.childMenus && item.childMenus.length > 0) {
          // item.disabled = true
          this.getData(item.childMenus)
        } else {
          // item.disabled = false
        }
      })
      return value
    },
    // 查询菜单
    async getMenu() {
      try {
        const {
          data: { items }
        } = await MenuSearch({ pageIndex: 1, pageSize: 1e8 })
        let id = null
        items.forEach((item) => {
          if (!item.parentId) {
            id = item.id
          }
        })
        this.getDataList(id)
      } catch (err) {
        console.log(err)
      }
    },
    // 设置合并单元格
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0 || columnIndex === 1) {
        const row = this.ary[rowIndex]
        const col = row > 0 ? 1 : 0
        return {
          rowspan: row,
          colspan: col
        }
      }
    },
    async getList() {
      try {
        this.tableLoading = true
        const obj = {
          pageIndex: this.page.num,
          pageSize: this.page.size,
          orderBy: 'createdTime',
          orderByAscent: false
          // search: [
          // {
          //   "key": "string",
          //   "value": {},
          //   "operation": 0,
          //   "sequence": 0,
          //   "relationship": 0,
          //   "priorities": [
          //     null
          //   ]
          // }
          // ],
          // orderBy: "createdTime",
          // orderByAscent: true,
          // select: [
          //   "name",
          //   'photo',
          //   'status'
          // ]
        }
        const res = await shareEmployeeHandle('post', obj, false)
        if (res.code === 200) {
          const ary = []
          this.tableValue = []
          res.data.items.forEach((item) => {
            item.newTime = parseTime(new Date(item.updatedTime), '{y}-{m}-{d} {h}:{i}:{s}')
            ary.push(item)
          })
          this.editList(ary)
          // this.$nextTick(() => {
          // this.$refs['RefListTable'].update({ page: pageIndex, count })
          this.page.total = res.data.count
          this.tableLoading = false
          // })
        }
      } catch (err) {
        this.tableLoading = false
        console.log(err)
      }
    },
    // 得到正确排序的员工列表
    editList(value) {
      const listary = []
      if (!value) {
        return
      }
      // 得到排序的数据
      value.forEach((item) => {
        if (!listary.includes(item.rfid)) {
          listary.push(item.rfid)
        }
      })
      // 得到渲染的列表数据
      listary.forEach((edit) => {
        value.forEach((itemValue) => {
          if (itemValue.rfid === edit) {
            this.tableValue.push({
              rfid: itemValue.rfid,
              shareStatus: itemValue.shareStatus,
              toTunnel: itemValue.toTunnel,
              newTime: itemValue.newTime,
              photo: itemValue.faceDetectPhoto1 ?? itemValue.photo,
              id: itemValue.id,
              name: itemValue.name
            })
          }
        })
      })

      const dataValue = JSON.parse(JSON.stringify(this.tableValue))
      // 清空合并单元格的数组
      this.ary = []
      // 重新获得合并单元格的数组
      dataValue.forEach((grain, index) => {
        let num = 0
        this.tableValue.forEach((edit, serialNumber) => {
          if (grain.rfid === edit.rfid) {
            num++
          }
        })
        this.ary.push(num)
      })
      const len = this.ary.length
      // 循环处理合并单元格的数据
      for (let i = 0; i <= len; i++) {
        if (this.ary[i] > 1) {
          const aryList = []
          for (let j = 0; j < this.ary[i] - 1; j++) {
            aryList.push(0)
          }
          this.ary.splice(i + 1, this.ary[i] - 1, ...aryList)
        }
      }
    },
    async delRowReq(row) {
      try {
        const obj = { id: row.id, value: null }
        await shareEmployeeHandle('delete', obj, true)
        this.getList()
        this.$message({
          type: 'success',
          message: '删除成功'
        })
      } catch (err) {
        this.$message({
          type: 'error',
          message: '删除失败'
        })
      }
    },
    deletHandle(row) {
      this.$confirm(`此操作将取消共享员工  ${row.name}  到  ${row.toTunnel}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.delRowReq(row)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作！'
          })
        })
    },
    // 分页页数改变
    handleCurrentChange(value) {
      this.page.num = value
      this.getList()
    },
    // 分页
    handleSizeChange(value) {
      this.page.size = value
      this.getList()
    }
  }
}
</script>

<style lang="scss" scoped>
  .box-card {
    ::v-deep.el-card__header {
      padding: 0px;
    }
  }
  .main {
    flex: 1;
  }
  .box {
    flex: 1;
    display: flex;
    align-items: center;
  }
  .page-list-live {
    min-height: calc(100vh - 50px);
    display: flex;
    flex-direction: column;
  }
  .el-row {
    display: flex;
    justify-content: space-between;
  }
  .header {
    display: flex;
    align-items: center;
    .div {
      flex: 1;
    }
  }
  .boxDiv-card {
    // ::v-deep.el-card__header {
    //   padding: 0px;
    // }
    ::v-deep.el-card__body {
      padding: 0px;
    }
  }
  .des {
    display: block;
    color: rgb(248, 70, 70);
  }
</style>
